package cn.qayy.controller;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.qayy.constants.CollectionConstant;
import cn.qayy.constants.Constant;
import cn.qayy.dto.CountryOver1k;
import cn.qayy.dto.ErrataDTO;
import cn.qayy.dto.KuCunDTO;
import cn.qayy.dto.KuncunListItem;
import cn.qayy.dto.Msg;
import cn.qayy.dto.MsgInfo;
import cn.qayy.dto.PlanVo;
import cn.qayy.dto.PlansDTO;
import cn.qayy.dto.QueryVO;
import cn.qayy.dto.Report3yearPlans;
import cn.qayy.dto.ReportPlans;
import cn.qayy.dto.TerminalOver1k;
import cn.qayy.dto.calsum;
import cn.qayy.dto.signInDTO;
import cn.qayy.po.KdbNssFocuson;
import cn.qayy.po.KdbNssGoodfriend;
import cn.qayy.po.Plan;
import cn.qayy.po.Policy;
import cn.qayy.po.Register;
import cn.qayy.po.Task;
import cn.qayy.po.User;
import cn.qayy.service.IBasisService;
import cn.qayy.service.IPlanService;
import cn.qayy.service.IPolicyService;
import cn.qayy.service.IRegisterService;
import cn.qayy.service.ISignInService;
import cn.qayy.service.SynchronizationService;
import cn.qayy.service.Uploadable;
import cn.qayy.utils.BeanToMapUtils;
import cn.qayy.utils.DateUtils;
import cn.qayy.utils.DownLoadUtil;
import cn.qayy.utils.ExcelUtils;
import cn.qayy.utils.InitPlansUtil;
import cn.qayy.utils.JsonUtil;
import cn.qayy.utils.ResonseUtils;
import cn.qayy.utils.StringUtil;
import cn.qayy.utils.UploadHandler;

/**
 * @author wangyu 流向表
 */
@Controller
@RequestMapping(value = "/plan/")
@SuppressWarnings("all")
public class PlanController {
	Logger log = Logger.getLogger(PlanController.class);

	// 注入service
	@Resource(name = "planServiceImpl")
	private IPlanService planService = null;

	@Resource(name = "registerServiceImpl")
	private IRegisterService registerService = null;

	@Resource(name = "policyServiceImpl")
	private IPolicyService policyService = null;

	@Resource(name = "synchronizationImpl")
	private SynchronizationService synchronizationService = null;
	
	@Resource(name = "signInServiceImpl")
	private ISignInService signInService = null;
	
	@Resource(name = "basisServiceImpl")
	private IBasisService basicService = null;
	
	List<String> multiselectCondi = new ArrayList<String>(); // 可多选的条件

	private List<Plan> selectByMap;

	/***
	 * 费用管理，查询协议相关数据自动填充
	 * @param startTime
	 * @param endTime
	 * @param customer
	 * @param terminal
	 * @param regulation
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "selectPolicy")
	public Object selectPolicy(String customer,String terminal,String regulation) {
		Msg msg = null;
		try {
			Map<String,Object> params = new HashMap<String,Object>();
			ArrayList<String> products = new ArrayList<String>();
			ArrayList<String> packs = new ArrayList<String>();
			ArrayList<String> cnames = new ArrayList<String>();
			ArrayList<Integer> status = new ArrayList<Integer>();
			//客户
			if(StringUtil.isNotBlank(customer)) {
				params.put("client", customer);
			}
			//品种、包装
			if(StringUtil.isNotBlank(regulation)) {
				String product = regulation.substring(0, 1);
				String pack = regulation.substring(1);
				products.add(product);
				packs.add(pack);
				params.put("products", products);
				params.put("packs", packs);
			}
			//入货乙方 Qs
			if(StringUtil.isNotBlank(terminal)) {
				params.put("terminalQs", terminal);
			}
			//排序
			params.put("sort", "mtime");
			//limit
			params.put("size", "1");
			//是否有协议
			params.put("hasPolicy", "有");
			
			if(StringUtil.isNotBlank(customer)&&StringUtil.isNotBlank(terminal)) {
				List<Plan> list = planService.selectByMap(params);
				if(list.size() == 0) {
					msg = new Msg(Constant.FAIL_CODE,"没有找到相关记录，请先填写客户、终端品规信息。若已填写后仍没有找到，请手动完善。");
				} else {
					msg = new Msg(Constant.SUCESSFUL_CODE,list.get(0));
				}
			} else {
				msg = new Msg(Constant.FAIL_CODE,"没有找到相关记录，请先填写客户、终端（区县）品规信息。若已填写后仍没有找到，请手动完善。");
			}
		} catch (Exception e) {
			//e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	
	/***
	 * 批量导入
	 * @param excelFile
	 * @param request
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "upload")
	public Object upload(MultipartFile excelFile, HttpServletRequest request, Model model) {
		Msg msg = null;
		int listSize = 0; // excel记录数
		try {
			Map<String, List<Uploadable>> map = UploadHandler.getLastData(excelFile, PlansDTO.class);
			
			if (map.get("fail") != null && !map.get("fail").isEmpty()) {
				// 前台提示消息
				List<Uploadable> list = map.get("fail");
				msg = new Msg(Constant.CHECK_CODE, list);
			} else {// DB持久化
				planService.persistence(map,request,null);
				if(map.get("totalCount") != null) {
					MsgInfo msgInfo = (MsgInfo)map.get("totalCount").get(0);
					listSize = StringUtil.parseInt(msgInfo.getErr_num());
				}
				msg = new Msg(Constant.SUCESSFUL_CODE, "总记录数：" + listSize + "，总成功数：" + listSize + "，请核查！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	
	/***
	 * 勘误上传,更新的流向数据，和协议无关，可以更新毕的流向。权限很大。
	 * 流向的渠道，参考协议的，平时不需要通过勘误表去更新流向
	 * @param excelFile
	 * @param request
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "errataUpload", produces = "application/json;charset=UTF-8")
	public String errataUpload(MultipartFile kanwuExcel, HttpServletRequest request, Model model) {
		String resultList = "";
		Msg msg = null;
		int listSize = 0; // excel记录数
		int doSize = 0; // 执行成功记录数
		boolean isUpdateTx = false;//是否更新了条线
		try {
			Map<String, List<Uploadable>> map = UploadHandler.getLastData(kanwuExcel, ErrataDTO.class);
			/**用户上传的总记录数**/
			MsgInfo msgInfo = (MsgInfo)map.get("totalCount").get(0);
			listSize = StringUtil.parseInt(msgInfo.getErr_num());
			
			if (map.get("fail") != null && !map.get("fail").isEmpty()) {// 前台提示消息
				/**
				 * 验证不通过，前台提示消息
				 */
				List<Uploadable> list = map.get("fail");
				msg = new Msg(Constant.CHECK_CODE, list);
				resultList = JSONObject.toJSONString(msg);
			} else {// DB持久化
				// 待更新的实体list
				List<Uploadable> listE = map.get("E");
				if (listE != null && !listE.isEmpty()) {
					/** 勘误表list **/
					List<ErrataDTO> list = new ArrayList<ErrataDTO>(listE.size() + 1);
					for (Uploadable u : listE) {
						ErrataDTO dto = (ErrataDTO) u;
						list.add(dto);
					}
					//流向的id
					List<Integer> ids = new ArrayList<Integer>(listE.size() + 1);
					for (ErrataDTO errataDTO : list) {
						ids.add(StringUtil.parseInt(errataDTO.getId())==null?0:StringUtil.parseInt(errataDTO.getId()));
					}
					Map<String, Object> params = new HashMap<String,Object>(Constant.INIT_CAPACITY);
					params.put("ids",ids);
					//从勘误表了里获取待更新的流向
					List<Plan> byMap = planService.selectByMap(params);
					Set<String> yifans = new HashSet<String>(byMap.size()+1);
					
					for (ErrataDTO dto : list) {
						for (Plan plan : byMap) {
							if(dto.getId().equals(plan.getId()+"")) {
								if(StringUtil.isNotBlank(dto.getZhenghe_qs())) {
									plan.setZhenghe_qs(dto.getZhenghe_qs());
								}
								if(StringUtil.isNotBlank(dto.getTerminaltype())) {
									plan.setTerminaltype(dto.getTerminaltype());
								}
								if(StringUtil.isNotBlank(dto.getTerminallev())) {
									plan.setTerminallev(dto.getTerminallev());
								}
								if(StringUtil.isNotBlank(dto.getXieyizhuangtai())) {
									plan.setXieyizhuangtai(dto.getXieyizhuangtai());
									isUpdateTx = true;
								}
								if(StringUtil.isNotBlank(dto.getFenbu())) {
									plan.setFenbu(dto.getFenbu());
								}
								if(StringUtil.isNotBlank(dto.getDaibiao())) {
									plan.setDaibiao(dto.getDaibiao());
								}
								if(StringUtil.isNotBlank(dto.getTichengbelong())) {
									plan.setTichengbelong(dto.getTichengbelong());
								}
								if(StringUtil.isNotBlank(dto.getPmode())) {
									plan.setMode(dto.getPmode());
								}
								if(StringUtil.isNotBlank(dto.getMoney6())) {
									plan.setMoney6(dto.getMoney6());
								}
								if(StringUtil.isNotBlank(dto.getStatus6())) {
									plan.setStatus6(dto.getStatus6());
								}
								if(StringUtil.isNotBlank(dto.getProvince())) {
									plan.setProvince(dto.getProvince());
								}
								if(StringUtil.isNotBlank(dto.getCity())) {
									plan.setCity(dto.getCity());
								}
								if(StringUtil.isNotBlank(dto.getCounty())) {
									plan.setCounty(dto.getCounty());
								}
								if(StringUtil.isNotBlank(dto.getDaqu())) {
									plan.setDaqu(dto.getDaqu());
									plan.setStatus8("ID");
								}
								if(StringUtil.isNotBlank(dto.getSpace())) {
									plan.setSpace(dto.getSpace());
									plan.setStatus8("ID");
								}
								if(StringUtil.isNotBlank(dto.getMgr())) {
									plan.setMgr(dto.getMgr());
									plan.setStatus8("ID");
								}
								if(StringUtil.isNotBlank(dto.getDemo())) {
									plan.setDemo(dto.getDemo());
								}
								plan.setMtime(new Date());
								yifans.add(plan.getTerminal());
								continue;
							}
						}
					}
					/** 更新勘误id对应的流向 允许对已毕流向就行更新 */
					doSize = doSize + planService.updateByListNoLimit(byMap,request);
					
					/***查询上面已经更新的入货乙方对应的其他流向**/
					Map<String, Object> params2 = new HashMap<String,Object>(Constant.INIT_CAPACITY);
					params2.put("terminals",yifans);
					List<Plan> byMap2 = planService.selectByMap(params2);
					for (Plan plan2 : byMap2) {
						for (Plan plan : byMap) {
							if(plan2.getTerminal().equals(plan.getTerminal())) {
								plan2.setZhenghe_qs(plan.getZhenghe_qs());
								plan2.setTerminaltype(plan.getTerminaltype());
								plan2.setTerminallev(plan.getTerminallev());
								continue;
							}
						}
					}
					/**更新其他流向的Qs名、类型、级别*/
					planService.updateOther(byMap2);
					/**同步更新注册库*/
					synchronizationService.plansUpdateRegister(yifans);
					List<Plan> addList = new ArrayList<Plan>(byMap.size()+byMap2.size()+1);
					addList.addAll(byMap);
					addList.addAll(byMap2);
					//基础库同步更新流向,并更新折量
					InitPlansUtil.synchronizationPlan(synchronizationService, addList);
				}
				/**
				 * 正常操作前台提示消息
				 */
				msg = new Msg(Constant.SUCESSFUL_CODE, "总记录数：" + listSize + "，总成功数：" + doSize + "，请核查！");
				resultList = JSONObject.toJSONString(msg);
			}
		} catch (Exception e) {
			/**
			 * 异常后的前台提示消息
			 */
			if(e.getMessage().contains("对应多个客户")) {
				msg = new Msg(Constant.FAIL_CODE,e.getMessage());
			}else {
				e.printStackTrace();
				msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
			}
			resultList = JsonUtil.object2json(msg);
		}
		return resultList;
	}
	
	/***
	 * 勘误页面批量更新流向,更新的流向数据，和协议无关，可以更新毕的流向
	 * @param vo
	 * @param request
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "errataUpdate")
	public String errataUpdate(QueryVO vo,HttpServletRequest request) {
		String resultList = "";
		Msg msg = null;
		try {
			String strId = vo.getId();
			List<String> id2List = StringUtil.strId2List(strId, " ");
			Map<String, Object> params = new HashMap<String,Object>(Constant.INIT_CAPACITY);
			params.put("ids",id2List);
			//从勘误表了里获取待更新的流向
			List<Plan> byMap = planService.selectByMap(params);
			ErrataDTO dto = vo.getErrataDTO();
			
			int listSize = 0; // excel记录数
			int doSize = 0; // 执行成功记录数
			boolean isUpdateTx = false;//是否更新了条线
			Map<String, List<Uploadable>> map = UploadHandler.getLastData(dto);
			/**用户上传的总记录数**/
			listSize = id2List.size();
			
			if (map.get("fail") != null && !map.get("fail").isEmpty()) {// 前台提示消息
				/**
				 * 验证不通过，前台提示消息
				 */
				List<Uploadable> list = map.get("fail");
				msg = new Msg(Constant.CHECK_CODE, list);
				resultList = JSONObject.toJSONString(msg);
			} else {// DB持久化
				List<Uploadable> listE = map.get("E");
				//验证通过
				if (listE != null && !listE.isEmpty()) {
					//存储更新过程中的乙方
					Set<String> yifans = new HashSet<String>(byMap.size()+1);
					
					for (Plan plan : byMap) {
						if(StringUtil.isNotBlank(dto.getZhenghe_qs())) {
							plan.setZhenghe_qs(dto.getZhenghe_qs());
						}
						if(StringUtil.isNotBlank(dto.getTerminaltype())) {
							plan.setTerminaltype(dto.getTerminaltype());
						}
						if(StringUtil.isNotBlank(dto.getTerminallev())) {
							plan.setTerminallev(dto.getTerminallev());
						}
						if(StringUtil.isNotBlank(dto.getXieyizhuangtai())) {
							plan.setXieyizhuangtai(dto.getXieyizhuangtai());
							isUpdateTx = true;
						}
						if(StringUtil.isNotBlank(dto.getFenbu())) {
							plan.setFenbu(dto.getFenbu());
						}
						if(StringUtil.isNotBlank(dto.getDaibiao())) {
							plan.setDaibiao(dto.getDaibiao());
						}
						if(StringUtil.isNotBlank(dto.getTichengbelong())) {
							plan.setTichengbelong(dto.getTichengbelong());
						}
						if(StringUtil.isNotBlank(dto.getPmode())) {
							plan.setMode(dto.getPmode());
						}
						if(StringUtil.isNotBlank(dto.getMoney6())) {
							plan.setMoney6(dto.getMoney6());
						}
						if(StringUtil.isNotBlank(dto.getStatus6())) {
							plan.setStatus6(dto.getStatus6());
						}
						//暂时关闭该修改权限
//						if(StringUtil.isNotBlank(dto.getProvince())) {
//							plan.setProvince(dto.getProvince());
//						}
						if(StringUtil.isNotBlank(dto.getCity())) {
							plan.setCity(dto.getCity());
						}
						if(StringUtil.isNotBlank(dto.getCounty())) {
							plan.setCounty(dto.getCounty());
						}
						if(StringUtil.isNotBlank(dto.getDaqu())) {
							plan.setDaqu(dto.getDaqu());
							plan.setStatus8("ID");
						}
						if(StringUtil.isNotBlank(dto.getSpace())) {
							plan.setSpace(dto.getSpace());
							plan.setStatus8("ID");
						}
						if(StringUtil.isNotBlank(dto.getMgr())) {
							plan.setMgr(dto.getMgr());
							plan.setStatus8("ID");
						}
						if(StringUtil.isNotBlank(dto.getDemo())) {
							plan.setDemo(dto.getDemo());
						}
						plan.setMtime(new Date());
						yifans.add(plan.getTerminal());
					}
					/** 更新勘误id对应的流向 */
					doSize = doSize + planService.updateByListNoLimit(byMap,request);
					
					/***查询上面已经更新的入货乙方对应的其他流向**/
					Map<String, Object> params2 = new HashMap<String,Object>(Constant.INIT_CAPACITY);
					params2.put("terminals",yifans);
					List<Plan> byMap2 = planService.selectByMap(params2);
					for (Plan plan2 : byMap2) {
						for (Plan plan : byMap) {
							if(plan2.getTerminal().equals(plan.getTerminal())) {
								plan2.setZhenghe_qs(plan.getZhenghe_qs());
								plan2.setTerminaltype(plan.getTerminaltype());
								plan2.setTerminallev(plan.getTerminallev());
								continue;
							}
						}
					}
					/**更新其他流向的Qs名、类型、级别*/
					planService.updateOther(byMap2);
					/**同步更新注册库*/
					synchronizationService.plansUpdateRegister(yifans);
					List<Plan> addList = new ArrayList<Plan>(byMap.size()+byMap2.size()+1);
					addList.addAll(byMap);
					addList.addAll(byMap2);
					//基础库同步更新流向,并更新折量
					InitPlansUtil.synchronizationPlan(synchronizationService, addList);
				}
				/**
				 * 正常操作前台提示消息
				 */
				msg = new Msg(Constant.SUCESSFUL_CODE, "总记录数：" + listSize + "，总成功数：" + doSize + "，请核查！");
				resultList = JSONObject.toJSONString(msg);
			}
		} catch (Exception e) {
			/**
			 * 异常后的前台提示消息
			 */
			if(e.getMessage().contains("对应多个客户")) {
				msg = new Msg(Constant.FAIL_CODE,e.getMessage());
			}else {
				e.printStackTrace();
				msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
			}
			resultList = JsonUtil.object2json(msg);
		}
		return resultList;
	}

	@ResponseBody
	@RequestMapping(value = "selectPlanList")
	public Object selectPlanList(PlanVo dto, HttpServletRequest request) {
		//对map进行过滤，除去空格
		Msg msg = null;
		try {
			Map<String,Object> parm = BeanToMapUtils.objectToMap_strong(dto);
			parm.put("mgr", dto.getMgr());
			parm.put("zhenghe_qs", dto.getZhenghe_qs());
			parm.put("fenbu", dto.getFenbu());
			parm.put("daibiao", dto.getDaibiao());
			parm.put("client", dto.getClient());
			parm.put("tichengbelong", dto.getTichengbelong());
			parm.put("terminal", dto.getTerminal());
			parm.put("commercial1", dto.getCommercial1());
			  
			parm.put("pageSize", dto.getPageSize());
			parm.put("pageNumber", dto.getPageNumber());
			parm.put("today", dto.getToday());
			parm.put("money6", dto.getMoney6());
			parm.put("unqualified",dto.getUnqualified());
			parm.put("status6", dto.getStatus6());
			PageInfo<Map<String,Object>> pageInfo = planService.selectPlanBy(parm);
			msg = new Msg(Constant.SUCESSFUL_CODE,pageInfo);
			
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	
	/*@ResponseBody
	@RequestMapping(value = "selectPlanList1")
	public String selectPlanList1(@RequestParam Map<String, Object> condiMap, HttpServletRequest request) {
		//对map进行过滤，除去空格
		condiMap = StringUtil.trim4Map(condiMap);
		String resultList = "";
		Msg msg = null;
		try {
			multiselectCondi.add("month");
			multiselectCondi.add("product");
			multiselectCondi.add("judge");
			multiselectCondi.add("pack");
			multiselectCondi.add("mode");
			multiselectCondi.add("xieyizhuangtai");
			multiselectCondi.add("terminaltype");
			multiselectCondi.add("kaipiaofangshi");
			multiselectCondi.add("jsmode");
			multiselectCondi.add("province");
			multiselectCondi.add("year");
			multiselectCondi.add("city");
			multiselectCondi.add("county");
			multiselectCondi.add("daqu");
			multiselectCondi.add("space");
			multiselectCondi.add("status3");
			multiselectCondi.add("tcstatus");
			multiselectCondi.add("status1");
			multiselectCondi.add("status4");
			multiselectCondi.add("status5");
			multiselectCondi.add("statusMgr");
			multiselectCondi.add("id");
			multiselectCondi.add("policyId");
			for (Object obj : condiMap.keySet()) {
				if (multiselectCondi.contains(obj)) {
					if (condiMap.get(obj).toString().startsWith("请选择")) {
						condiMap.put(obj.toString(), null);
					} else if (condiMap.get(obj) != null) {
						if (obj.equals("id")||obj.equals("policyId")) {
							String[] array = StringUtil.strToArray((String) condiMap.get(obj), " ");
							if (array != null) {
								condiMap.put(obj.toString(), array);
							} else {
								condiMap.put(obj.toString(), null);
							}
						} else {
							String[] array = StringUtil.strToArray(StringUtil.trimAll((String) condiMap.get(obj)), ",");
							if (array != null) {
								condiMap.put(obj.toString(), array);
							} else {
								condiMap.put(obj.toString(), null);
							}
						}
					}
				} else if (condiMap.get(obj).equals("")) {
					condiMap.put(obj.toString(), null);
				}
			}
			// 获取当前登录用户的权限（age）
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute("user");
			PageInfo<Map<String, Object>> listMap = planService.selectPlanBy(condiMap);
			resultList = JSONObject.toJSONString(listMap);
			return resultList;
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
			resultList = JsonUtil.object2json(msg);
		}
		return resultList;
	}*/


	@ResponseBody
	@RequestMapping(value = "selectPlanByID")
	public Object selectPlanByID(@RequestParam Integer planId) {
		String resultList = "";
		Msg msg = null;
		try {
			Plan plan = planService.selectPlanByID(planId);
			Object obj = JSONObject.toJSON(plan);
			return obj;
		} catch (Exception e) {
			/**
			 * 异常后的前台提示消息
			 */
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
			resultList = JsonUtil.object2json(msg);
		}
		return resultList;
	}

	/***
	 * 财务对流向的押待毕操作
	 * @param statusMap
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "caiwu/changeStatus")
	public Object changeStatus(QueryVO vo,HttpServletRequest request) {
		Msg msg = null;
        //封装数据
        int doSize = 0;
		try {
			//获取到流向id
			List<String> id2List = StringUtil.strId2List(vo.getId()," ");
			if(id2List.size()>=2001) {
				msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG2000);
				return msg;
			}
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("ids", id2List);
			//查询到目标待修改的流向列表
			List<Plan> plans = planService.selectByMap(params);
			HttpSession session = request.getSession();
	        User user = (User)session.getAttribute("user");
	        
	        //已毕的ids
	        StringBuffer bi1edIds = new StringBuffer("");
	        StringBuffer bi3edIds = new StringBuffer("");
	        StringBuffer bi4edIds = new StringBuffer("");
	        StringBuffer bi5edIds = new StringBuffer("");
	        StringBuffer biywyedIds = new StringBuffer("");
	        StringBuffer bitcedIds = new StringBuffer("");
	        
			for (Plan p : plans) {
				for(String type:vo.getTypes().split(",")) {
					String vostatus = StringUtil.trimAll(vo.getStatus());
					//1服务费（推广）
					if("1".equals(type)) {
						if(p.getStatus1().contains("毕")) {
							bi1edIds.append(p.getId()).append(" ");
						} else {
							p.setStatus1(vostatus);
							p.setMtime(new Date());
							p.setDataer(user.getUser_name());
						}
					}
					//3发票服务费
					if("3".equals(type)) {
						if(p.getStatus3().contains("毕")) {
							bi3edIds.append(p.getId()).append(" ");
						} else {
							p.setStatus3(vostatus);
							p.setMtime(new Date());
							p.setDataer(user.getUser_name());
						}
					}
					
					//达标费
					if("4".equals(type)) {
						if(p.getStatus4().contains("毕")) {
							bi4edIds.append(p.getId()).append(" ");
						} else {
							p.setStatus4(vostatus);
							p.setMtime(new Date());
							p.setDataer(user.getUser_name());
						}
					}
					//开发奖励
					if("5".equals(type)) {
						if(p.getStatus5().contains("毕")) {
							bi5edIds.append(p.getId()).append(" ");
						} else {
							p.setStatus5(vostatus);
							p.setMtime(new Date());
							p.setDataer(user.getUser_name());
						}
					}
					//业务员奖励
					if("ywy".equals(type)) {
						if(p.getStatusMgr().contains("毕")) {
							biywyedIds.append(p.getId()).append(" ");
						} else {
							p.setStatusMgr(vostatus);
							p.setMtime(new Date());
							p.setDataer(user.getUser_name());
						}
					}
					//提成
					if("tc".equals(type)) {
						if(vostatus.contains("毕")&&p.getTcstatus().contains("毕")) {
							bitcedIds.append(p.getId()).append(" ");
						} else {
							p.setTcstatus(vostatus);
							p.setMtime(new Date());
							p.setDataer(user.getUser_name());
						}
					}
				}
			}
			StringBuffer sb = new StringBuffer();
			//看是否存在已毕的流向
			if(StringUtil.isNotBlank(bi1edIds.toString())) {
				if(StringUtil.isNotBlank(sb.toString())) {
					sb.append("<br>");
				}
				sb.append("【1服务费(推广)】这些id已毕：【"+bi1edIds.toString()+"】");
			}
			if(StringUtil.isNotBlank(bi3edIds.toString())) {
				if(StringUtil.isNotBlank(sb.toString())) {
					sb.append("<br>");
				}
				sb.append("【3服务费(发票)】这些id已毕：【"+bi3edIds.toString()+"】");
			}
			if(StringUtil.isNotBlank(bi4edIds.toString())) {
				if(StringUtil.isNotBlank(sb.toString())) {
					sb.append("<br>");
				}
				sb.append("【4服务费(达标)】这些id已毕：【"+bi4edIds.toString()+"】");
			}
			if(StringUtil.isNotBlank(bi5edIds.toString())) {
				if(StringUtil.isNotBlank(sb.toString())) {
					sb.append("<br>");
				}
				sb.append("【5开发奖励】这些id已毕：【"+bi5edIds.toString()+"】");
			}
			if(StringUtil.isNotBlank(biywyedIds.toString())) {
				if(StringUtil.isNotBlank(sb.toString())) {
					sb.append("<br>");
				}
				sb.append("【业务员奖励】这些id已毕：【"+biywyedIds.toString()+"】");
			}
			if(StringUtil.isNotBlank(bitcedIds.toString())) {
				if(StringUtil.isNotBlank(sb.toString())) {
					sb.append("<br>");
				}
				sb.append("【提成 】这些id已毕：【"+bitcedIds.toString()+"】");
			}
			
			if(StringUtil.isNotBlank(sb.toString())) {
				msg = new Msg(Constant.FAIL_CODE,sb.toString());
				return msg;
			}
			
			//更新流向
			doSize = planService.updateByListNoLimit(plans,request);
			msg = new Msg(Constant.SUCESSFUL_CODE,"总记录数：" + id2List.size() + "，总成功数：" + doSize + "，请核查！");
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
		}
        return msg;
	}

	/**
	 * @author wangyu 重点终端、好伙伴的新增与修改
	 */
	@ResponseBody
	@RequestMapping(value = "changeKeyTerminal")
	public Object changeKeyTerminal(@RequestParam Map<String, Object> keyMap) {
		String result = "";
		try {
			//把以空格隔开的id转换成数组
			String[] ids = StringUtil.strDouHaoId2StrArray((String) keyMap.get("keyIds"), " ");
			keyMap.put("id", ids);
			// 封装数据
			int ret = planService.changeTerminal(keyMap);
			if (ret > 0) {
				Msg msg = new Msg(Constant.SUCESSFUL_CODE, Constant.SUCESSFUL_MSG);
				result = JsonUtil.object2json(msg);
			} else {
				Msg msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG);
				result = JsonUtil.object2json(msg);
			}
		} catch (Exception e) {
			/**
			 * 异常后的前台提示消息
			 */
			e.printStackTrace();
			Msg msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
			result = JsonUtil.object2json(msg);
		}
		return JSONObject.toJSON(result);
	}

	/***
	 * 页面新增、修改流向，只能修改非毕流向
	 * 
	 * @param dto
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "changePlan")
	public Object changePlan(PlansDTO dto, HttpServletRequest request) {
		Msg msg = null;
		String flag = (String) request.getParameter("flag");
		dto.setIsUpdate(flag);
		try {
			// 验证数据
			Map<String, List<Uploadable>> map = UploadHandler.getLastData(dto);
			if (map.get("fail") != null && !map.get("fail").isEmpty()) {
				List<Uploadable> list = map.get("fail");
				msg = new Msg(Constant.CHECK_CODE, list);
			} else {// 验证通过，DB持久化
				planService.persistence(map,request,null);
				msg = new Msg(Constant.SUCESSFUL_CODE, "总记录数：" + 1 + "，总成功数：" + 1 + "，请核查！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	
	/***
	 * 通过id修改流向属性,修改一些和协议无关的数据，可以修改毕的流向
	 * 修改：经理、片区提成人、大区提成人、条线
	 * @param plan
	 * @return
	 */
	@ResponseBody
    @RequestMapping(value="updatePlanByID")
    public Object updatePlanByID(QueryVO vo,HttpServletRequest request){
        Msg msg = null;
        //封装数据
        int doSize = 0;
		try {
			//获取到协议id
			List<String> id2List = StringUtil.strId2List(vo.getId()," ");
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("ids", id2List);
			List<Plan> plans = planService.selectByMap(params);
			for (Plan p : plans) {
				if(StringUtil.isNotBlank(StringUtil.trimAll(vo.getMgr()))) {
					p.setMgr(StringUtil.trimAll(vo.getMgr()));
					p.setStatus8("ID");
				}
				if(StringUtil.isNotBlank(StringUtil.trimAll(vo.getTichengbelong()))) {
					p.setTichengbelong(vo.getTichengbelong());
				}
				if(StringUtil.isNotBlank(StringUtil.trimAll(vo.getDaquTcMan()))) {
					p.setDaquTcMan(vo.getDaquTcMan());
				}
				if(StringUtil.isNotBlank(StringUtil.trimAll(vo.getXieyizhuangtai()))) {
					p.setXieyizhuangtai(vo.getXieyizhuangtai());
				}
				//暂时关闭其修改权限
//				if(StringUtil.isNotBlank(StringUtil.trimAll(vo.getClient()))) {
//					p.setClient(vo.getClient());
//				}
				if(StringUtil.isNotBlank(StringUtil.trimAll(vo.getDaibiao()))) {
					p.setDaibiao(vo.getDaibiao());
				}
			}
			if(!plans.isEmpty()) {
				doSize = planService.updateNomit(plans,request);
				msg = new Msg(Constant.SUCESSFUL_CODE,"总记录数：" + id2List.size() + "，总成功数：" + doSize + "，请核查！");
			} else {
				throw new Exception("对应id，找不到相关流向");
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
		}
        return msg;
    }
	
	/***
	 * 通过id修改流向属性,修改一些和协议无关的数据，可以修改毕的流向
	 * 修改：经理、片区提成人、大区提成人、条线
	 * @param plan
	 * @return
	 */
	@ResponseBody
    @RequestMapping(value="updatePriceByID")
    public Object updatePriceByID(String id,String price,String type){
        Msg msg = null;
        //封装数据
        int doSize = 0;
		try {
			//获取到协议id
			List<String> id2List = StringUtil.strId2List(id," ");
			Map<String, Object> params = new HashMap<String,Object>();
			if (id2List != null && !id2List.isEmpty()) {
				params.put("ids", id2List);
				List<Plan> plans = planService.selectByMap(params);
				if(!plans.isEmpty()) {
					for (Plan p : plans) {
						if(type.equals("1")) {	
							p.setYinyukaiguan(price);//开票价
						}else {
							p.setAtsum(price);//协议测算价
						}
					}
					//更新流向
					doSize = planService.updateByList(plans);
					msg = new Msg(Constant.SUCESSFUL_CODE,"总记录数：" + id2List.size() + "，总成功数：" + id2List.size() + "，请核查！");
				} else {
					msg = new Msg(Constant.CHECK_CODE,"没有找到待修改的流向，请认真检查流向id");
				}
			} else {
				msg = new Msg(Constant.CHECK_CODE,"没有找到待修改的流向，请认真检查流向id");
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
		}
        return msg;
    }
	
	/***
	 * 解锁，修改一些和协议无关的数据，可以修改毕的流向
	 */
	@ResponseBody
	@RequestMapping(value="notLock")
	public Object notLock(QueryVO vo,HttpServletRequest request){
		Msg msg = null;
		//封装数据
		int doSize = 0;
		try {
			//获取到协议id
			List<String> id2List = StringUtil.strId2List(vo.getId()," ");
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("ids", id2List);
			List<Plan> plans = planService.selectByMap(params);
			for (Plan p : plans) {
				p.setStatus8("");
			}
			if(!plans.isEmpty()) {
				//更新流向
				doSize = planService.updateByListNoLimit(plans,request);
				//基础库同步更新流向
				InitPlansUtil.synchronizationPlan(synchronizationService, plans);
				msg = new Msg(Constant.SUCESSFUL_CODE,"总记录数：" + id2List.size() + "，总成功数：" + doSize + "，请核查！");
			} else {
				throw new Exception();
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}

	/***
	 * 页面下载已筛选的记录
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "download")
	public void download(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<PlansDTO> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(PlansDTO.class);
			String downloadPath = ExcelUtils.getInstance().dataToExcelDxls("流向表",StringUtil.listToStrArray(CollectionConstant.plans_mb),loadDataList);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	/***
	 * 页面下载已筛选的所有字段对应的记录
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "downloadAll")
	public void downloadAll(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<ReportPlans> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(ReportPlans.class);
			String downloadPath = ExcelUtils.getInstance().dataToExcelDxls("流向表",StringUtil.listToStrArray(CollectionConstant.plans_notes),loadDataList);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	
	/***
	 * 下载近3年的所有纯销
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "download3yearAll")
	public void download3yearAll(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<Report3yearPlans> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(Report3yearPlans.class);
			//csv方式
			String filePath = ExcelUtils.exportCVS(loadDataList, StringUtil.listToArray(CollectionConstant.report3yearPlansMB));
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+filePath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	
	
	/***
	 * 好伙伴页面下载已筛选的记录
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "gf_download")
	public void gf_download(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<KdbNssGoodfriend> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(KdbNssGoodfriend.class);
			String downloadPath = ExcelUtils.getInstance().dataToExcelDxls("好伙伴",StringUtil.listToStrArray(CollectionConstant.goodfriden_mb),loadDataList);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	/***
	 * 重点终端页面下载已筛选的记录
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "focus_download")
	public void focus_download(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<KdbNssFocuson> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(KdbNssFocuson.class);
			String downloadPath = ExcelUtils.getInstance().dataToExcelDxls("重点终端",StringUtil.listToStrArray(CollectionConstant.focus_mb),loadDataList);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	/***
	 * 勘误表下载已筛选的记录
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "errata_download")
	public void errata_download(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<ErrataDTO> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(ErrataDTO.class);
			String downloadPath = ExcelUtils.getInstance().dataToExcelDxls("勘误表",StringUtil.listToStrArray(CollectionConstant.errata_mb),loadDataList);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	
	/***
	 * 展示UI页面
	 * @return
	 */
	@RequestMapping(value="ui")
	public String ui() {
		return "plans_search";
	}
	/***
	 * 好伙伴展示UI页面
	 * @return
	 */
	@RequestMapping(value="goodfriend_ui")
	public String goodfriend_ui() {
		return "goodFriend";
	}
	/***
	 * 重点终端展示UI页面
	 * @return
	 */
	@RequestMapping(value="focusOn_ui")
	public String focusOn_ui() {
		return "focusOn";
	}
	
	/***
	 * testUI页面
	 * @return
	 */
	@RequestMapping(value="test")
	public String test() {
		return "plans_query";
	}
	
	/***
	 * 删除流向
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "delPlan")
	public Object deletePlanByIDs(String id) {
		Msg msg = null;
		int doSize = 0;
		try {
			List<String> idList = StringUtil.strId2List(id," ");
			doSize = planService.deleteByIdList(idList);
			/**
			 * 正常操作前台提示消息
			 */
			msg = new Msg(Constant.SUCESSFUL_CODE,"总记录数：" + idList.size() + "，总成功数：" + doSize + "，请核查！");
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	
	/***
	 * 赋值政策，手动匹配政策，只影响非毕流向
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="initPolicy")
	public String initPolicy(QueryVO vo) {
		Msg msg = null;
		String result = ""; // 返回结果
		try {
			//获取到协议id
			List<String> policyId_List = StringUtil.strId2List(vo.getPolicy_Id()," ");
			//获取到流向id
			List<String> planId_List = StringUtil.strId2List(vo.getPlan_Id()," ");
			if(policyId_List.size() != 1) {
				msg = new Msg(Constant.FAIL_CODE, "只能输入一个正确的协议id");
				result = JsonUtil.object2json(msg);
				return result;
			}
			Policy policy = policyService.selectPolicyByID(StringUtil.parseInt(policyId_List.get(0)));
			if(policy == null) {
				msg = new Msg(Constant.FAIL_CODE, "只能输入一个正确的协议id");
				result = JsonUtil.object2json(msg);
				return result;
			}
			if(policy.getGuihuanriqi().equals("3")) {
				msg = new Msg(Constant.FAIL_CODE, "只能输入一个正确有效的协议id");
				result = JsonUtil.object2json(msg);
				return result;
			}
			
			Set<String> ppStrs = new HashSet<String>();
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("ids", planId_List);
			List<Plan> list = planService.selectByMap(params);
			for (Plan plan : list) {
				ppStrs.add(plan.getClient()+plan.getProduct()+plan.getPack());
			}
			if(ppStrs.size()==0 || ppStrs.size()>=2) {
				throw new Exception("流向的客户、品种、包装和协议不匹配，无法完成匹配工作");
			}
			for(String s:ppStrs) {
				if(!s.equals(policy.getClient()+policy.getProduct()+policy.getPage())) {
					throw new Exception("流向的客户、品种、包装和协议不匹配，无法完成匹配工作");
				}
			}
			
			for (Plan plan : list) {
				plan.setMtime(new Date());
				// 协议开始时间<=流向时间<协议结束时间
				if(DateUtils.isDateGt2Eq(plan.getSdate(),policy.getXieyistarttime())
						&&DateUtils.isDateLt(plan.getSdate(),policy.getXieyiendtime())) {
					InitPlansUtil.policy_into_logs(plan, policy);
					plan.setStatus7("手动匹配政策");
				} else {
					throw new Exception("流向的日期不在协议的有效日期之内，无法完成匹配工作");
				}
			}
			planService.updateByList(list);
			msg = new Msg(Constant.SUCESSFUL_CODE, Constant.SUCESSFUL_MSG);
		} catch(Exception e) {
			if(e.getMessage().contains("无法完成匹配工作")) {
				msg = new Msg(Constant.FAIL_CODE,e.getMessage());
			} else {
				e.printStackTrace();
				msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
			}
		}
		result = JsonUtil.object2json(msg);
		return  result;
	}
	/***
	 * 下载时间理论库存
	 * @return
	 */
	@RequestMapping(value="downloadTimeInventory")
	public void downloadTimeInventory(QueryVO vo,HttpServletRequest request,HttpServletResponse response,Model model) {
		Msg msg = null;
		String result = ""; // 返回结果
		try {
			//获取到截止时间
			String etime = DateUtils.parseDate(vo.getEndTime());
			String year = DateUtils.getYear(etime);
			//入货乙方对应的省份，给库存的商业公司赋值省份
			Map<String,String> map = new HashMap<String,String>(Constant.CENTER_CAPACITY/2);
			//入货乙方对应的标识flag，给库存的商业ID赋值，标识该商业是否是有ID账号的
			Map<String,String> mapID = new HashMap<String,String>(Constant.CENTER_CAPACITY/2);
			List<Register> rs = new ArrayList<Register>(Constant.CENTER_CAPACITY/2);
			rs.addAll(registerService.selectAllProvince2Names());
			for (Register register : rs) {
				map.put(register.getCname(),register.getShengfen());
				mapID.put(register.getCname(),register.getFlag());
			}
			//计算当前年，且到截止日期的库存
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("year",year);
			params.put("etime",etime);
			List<Plan> listYifan = planService.selectYifanKuCun(params);
			List<Plan> listJiafan = planService.selectJiafanKuCun(params);
			//下载计算后的时间理论库存
			List<KuncunListItem> kuCun = InitPlansUtil.calculateKuCun(year, etime,map,mapID,listYifan,listJiafan);
			List<KuCunDTO> targets = new ArrayList<KuCunDTO>(kuCun.size()+1);
			List<KuCunDTO> myTargets = new ArrayList<KuCunDTO>();
			for (KuncunListItem ki : kuCun) {
				KuCunDTO dto = new KuCunDTO(
						ki.getCompanyID(),
						ki.getCompany(),ki.getProvince(),ki.getTx(),ki.getPmode(),
						ki.getClient(),ki.getProduct(),ki.getPack(),ki.getQichu(),
						ki.getXiaoshou(),ki.getDiaojing(),ki.getDiaochu(),ki.getCunxiao(),
						ki.getKucun(),ki.getEtime(),ki.getQichuScount(),ki.getXiaoshouScount(),
						ki.getDiaojingScount(),ki.getDiaochuScount(),
						ki.getCunxiaoScount(),ki.getKucunScount());
				targets.add(dto);
			}
			HttpSession session = request.getSession();
	        User user = (User)session.getAttribute("user");
	        List<String> mgrProvinces = basicService.selectProvinceByMgr(user.getUser_name());
	        if(user.getAge() == 0) {
	        	for(String p:mgrProvinces) {
	        		KuCunDTO dto = new KuCunDTO();
	        		dto.setProvince(p);
	        		myTargets.add(dto);
	        	}
	        	targets.retainAll(myTargets);
	        }
	        
			JSONObject json = new JSONObject();
			//把数据写入到Excel并返回文件路径和文件 targets下载源数据，后面是标题字符串数组
	        String filePath = ExcelUtils.exportCVS(targets, StringUtil.listToArray(CollectionConstant.kucun_mb));
	        json.put("sucessful", 1);//关闭进度条
	        json.put("filePath", "/servlet/FileDownServlet?url=" + filePath);//文件下载,请求Servlet
	        ResonseUtils.writeResponseByJson(response, json);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	/***
	 * 下载经理签到
	 * @return
	 */
	@RequestMapping(value="downloadMgrQianDao")
	public void downloadMgrQianDao(QueryVO vo,HttpServletRequest request,HttpServletResponse response,Model model) {
		Msg msg = null;
		String result = ""; // 返回结果
		try {
			//获取到截止时间
			String startTime = DateUtils.parseDate(vo.getStartTime());
			String endTime = DateUtils.parseDate(vo.getEndTime());
			//入货乙方对应的省份，给库存的商业公司赋值省份
			Map<String,String> map = new HashMap<String,String>(Constant.CENTER_CAPACITY/2);
			List<Register> rs = new ArrayList<Register>(Constant.CENTER_CAPACITY/2);
			rs.addAll(registerService.selectAllProvince2Names());
			for (Register register : rs) {
				map.put(register.getCname(),register.getShengfen());
			}
			
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("startTime",startTime);
			params.put("endTime",endTime);
			List<signInDTO> list = signInService.selectSignInForDown(params);
			List<signInDTO> myList = new ArrayList<signInDTO>();
			HttpSession session = request.getSession();
	        User user = (User)session.getAttribute("user");
	        if(user.getAge() == 0) {
	        	Map<String, Object> params_mgr = new HashMap<String,Object>();
	        	params_mgr.put("mgr",user.getUser_name());
	        	List<String> mgrs = basicService.selectMgrOfProvinceByMgr(params_mgr);
	        	for (String mgr : mgrs) {
	        		signInDTO dto = new signInDTO();
		        	dto.setName(mgr);
		        	myList.add(dto);
				}
	        	list.retainAll(myList);
	        }
			JSONObject json = new JSONObject();
			//把数据写入到Excel并返回文件路径和文件 targets下载源数据，后面是标题字符串数组
			String filePath = ExcelUtils.exportCVS(list, StringUtil.listToArray(CollectionConstant.qiandao_mb));
			json.put("sucessful", 1);//关闭进度条
			json.put("filePath", "/servlet/FileDownServlet?url=" + filePath);//文件下载,请求Servlet
			ResonseUtils.writeResponseByJson(response, json);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	/***
	 * 下载千盒区县情况
	 * @return
	 */
	@RequestMapping(value="downloadCountryOver1k")
	public void downloadCountryOver1k(QueryVO vo,HttpServletRequest request,HttpServletResponse response,Model model) {
		Msg msg = null;
		String result = ""; // 返回结果
		try {
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("startMonth",vo.getStartMonth());
			params.put("endMonth",vo.getEndMonth());
			params.put("year",vo.getYear());
			params.put("product",vo.getProduct());
			params.put("judge","纯销");
			CountryOver1k t = new CountryOver1k();
			if("1".equals(vo.getStartMonth())) {
				t.setFlag("Q1");
			}
			if("4".equals(vo.getStartMonth())) {
				t.setFlag("Q2");
			}
			if("7".equals(vo.getStartMonth())) {
				t.setFlag("Q3");
			}
			if("10".equals(vo.getStartMonth())) {
				t.setFlag("Q4");
			}
			List<CountryOver1k> list = new ArrayList<CountryOver1k>();
			list.add(t); 
			list.addAll(planService.selectCountryOver1k(params));
			JSONObject json = new JSONObject();
			//把数据写入到Excel并返回文件路径和文件 targets下载源数据，后面是标题字符串数组
			String filePath = ExcelUtils.exportCVS(list, StringUtil.listToArray(CollectionConstant.countryOver1k_mb));
			json.put("sucessful", 1);//关闭进度条
			json.put("filePath", "/servlet/FileDownServlet?url=" + filePath);//文件下载,请求Servlet
			ResonseUtils.writeResponseByJson(response, json);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	/***
	 * 下载千盒终端情况
	 * @return
	 */
	@RequestMapping(value="downloadTerminalOver1k")
	public void downloadTerminalOver1k(QueryVO vo,HttpServletRequest request,HttpServletResponse response,Model model) {
		Msg msg = null;
		String result = ""; // 返回结果
		try {
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("startMonth",vo.getStartMonth());
			params.put("endMonth",vo.getEndMonth());
			params.put("year",DateUtils.getCurrentYear());
			params.put("product",vo.getProduct());
			params.put("judge","纯销");
			TerminalOver1k t = new TerminalOver1k();
			if("1".equals(vo.getStartMonth())) {
				t.setFlag("Q1");
			}
			if("4".equals(vo.getStartMonth())) {
				t.setFlag("Q2");
			}
			if("7".equals(vo.getStartMonth())) {
				t.setFlag("Q3");
			}
			if("10".equals(vo.getStartMonth())) {
				t.setFlag("Q4");
			}
			List<TerminalOver1k> list = new ArrayList<TerminalOver1k>();
			list.add(t);
			list.addAll(planService.selectTerminalOver1k(params));
			JSONObject json = new JSONObject();
			//把数据写入到Excel并返回文件路径和文件 targets下载源数据，后面是标题字符串数组
			String filePath = ExcelUtils.exportCVS(list, StringUtil.listToArray(CollectionConstant.terminalOver1k));
			json.put("sucessful", 1);//关闭进度条
			json.put("filePath", "/servlet/FileDownServlet?url=" + filePath);//文件下载,请求Servlet
			ResonseUtils.writeResponseByJson(response, json);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	/***
	 * 计算总和，按模式求和
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "selectSumBy")
	public Object selectSumBy() {
		String result;
		//获取缓存中的筛选条件
		Map<String, Object> params = (Map<String, Object>)DownLoadUtil.get("PlansDTO");
		if(params == null) {
			params = new HashMap<String, Object>();
			params.put("t", "1127");
		}
		//格式化筛选条件
		//到数据库中计算总和
		calsum calsum = planService.selectSumBy(params);
		List<calsum> list = new ArrayList<calsum>();
		if(calsum != null) {
			calsum.setMode("");
			list.add(calsum);
			List<calsum> list2 = planService.selectSumByMode(params);
			list.addAll(list2);
			for (calsum calsum2 : list) {
				System.out.println(calsum2);
			}
		}
		return list;
	}
	/***
	 * 获取待复制的id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "selectIds")
	public Object selectIds(HttpServletResponse response,HttpServletRequest request) {
		JSONObject json = new JSONObject();
		StringBuilder result=new StringBuilder();
		Msg msg = null;
		try {
			//获取缓存中的筛选条件
			Map<String, Object> params = (Map<String, Object>)DownLoadUtil.get("PlansDTO");
			if(params == null) {
				params = new HashMap<String, Object>();
				params.put("t", "1127");
			}
			List<Integer> list = planService.selectIdsByMap(params);
			if(list != null &&!list.isEmpty()) {
				for (Integer id : list) {
					result.append(id+" ");
				}
				result.deleteCharAt(result.length()-1);
			}
		} catch(Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
			return msg;
		}
		json.put("ids", result.toString());
		ResonseUtils.writeResponseByJson(response, json);
		//封装成json返回给前台
		return null;
	}
	
}
